package com.hdoit.apollo.web.stock.controllers;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.apollo.logical.common.enums.inventory.EndType;
import com.hdoit.apollo.logical.common.enums.inventory.InventoryState;
import com.hdoit.apollo.logical.common.enums.inventory.InventoryType;
import com.hdoit.apollo.logical.inventory.model.Inventory;
import com.hdoit.apollo.logical.inventory.model.InventoryShow;
import com.hdoit.apollo.logical.inventory.service.IInventoryService;
import com.hdoit.apollo.logical.inventory.service.IInventoryShowService;
import com.hdoit.apollo.logical.shop.model.Shop;
import com.hdoit.apollo.logical.stock.model.Stock;
import com.hdoit.apollo.logical.stock.service.IStockService;
import com.hdoit.apollo.logical.viewmodel.stock.InventoryCollocationInfo;
import com.hdoit.apollo.logical.viewmodel.stock.InventorySearch;
import com.hdoit.apollo.logical.viewmodel.stock.InventoryShowSearch;
import com.hdoit.apollo.logical.viewmodel.stock.StockSearch;
import com.tennetcn.authority.component.web.ActionResult;
import com.tennetcn.authority.component.web.BaseController;
import com.tennetcn.authority.component.web.ErrorResult;
import com.tennetcn.authority.component.web.JsonActionResult;
import com.tennetcn.core.common.enums.pub.YesOrNoInteger;
import com.tennetcn.core.common.message.ManageContainer;
import com.tennetcn.core.common.utils.CommonUtils;
import com.tennetcn.core.common.utils.DateUtils;
import com.tennetcn.core.common.utils.JsonUtils;
import com.tennetcn.data.enums.ModelStatus;
import com.tennetcn.data.message.PagerModel;
import com.tennetcn.web.message.WebManageContainer;

/**
 * @author      tancongzhu
 * @email       
 * @createtime  2018年05月30日 09:45:51
 * @comment
 */
@Controller
@RequestMapping(value = "/stock/inventory/")
public class InventoryController extends BaseController{
    @Override
    public String getRoutePath() {
        return "areas/stock/inventory/";
    }

    @Autowired
    private IInventoryService inventoryService;
    
    @Autowired
    private IInventoryShowService inventoryShowService;
    
    @Autowired
    private IStockService stockService;

    private final String indexViewName="index";
    private final String outputViewName="output";
    private final String detailedViewName="detailed";
    private final String saveViewName="save";
    private final String deleteViewName = "delete";
    private final String queryCargosViewName = "queryCargos";
    private final String selDetailed="selDetailed";
    private final String editDetailed="editDetailed";
    private final String saveInventoryShow = "saveInventoryShow";

    @RequestMapping(value = indexViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String index(Model model,PagerModel pagerModel,InventorySearch search,boolean ajaxPost){

        pagerModel.setTotalAmount(inventoryService.queryCountList(search));
        List<Inventory> inventorys= inventoryService.queryListList(search,pagerModel);

        model.addAttribute(WebManageContainer.PAGERKEY, pagerModel);
        model.addAttribute("inventorys", inventorys);
        model.addAttribute("inventorySearch", search);

        if(ajaxPost){
            return view(outputViewName);
        }

        return view(indexViewName);
    }

    @RequestMapping(value = detailedViewName, method = { RequestMethod.GET})
    public String inventoryDetailed(Model model,String key){
    	Inventory inventory=new Inventory();
        StockSearch stockSearch=new StockSearch();
        inventory.setCreateDate(DateUtils.getCurrent());
        inventory.setCreateDate(DateUtils.getCurrent());
        inventory.setCreateUserId(getLoginModel().getLoginId());
        inventory.setCreateUserName(getLoginModel().getLoginName());
        inventory.setInventoryNo("PD-"+ DateUtils.convertDate2String("yyyyMMddHHmmss",DateUtils.getCurrent()));

		model.addAttribute("stocksJson", JsonUtils.writeValueAsString(stockService.queryListMP(stockSearch,null)));
		model.addAttribute("stockSearch", stockSearch);
		model.addAttribute("inventory", inventory);
        return view(detailedViewName);
    }

    @RequestMapping(value = saveViewName, method = { RequestMethod.POST})
    public String save(Model model,Inventory inventory){
        if(StringUtils.isEmpty(inventory.getInventoryId())){
        	inventory.setInventoryId(CommonUtils.getKeyId());
        	
        	inventory.setEndType(EndType.unAdjustment);
        	inventory.setInventoryType(InventoryType.adjustment);
        	inventory.setInventoryState(InventoryState.pandianzhong);
        	
        	inventory.setDeleteMark(YesOrNoInteger.no);
            Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
            inventory.setShopId(shop.getShopId());
        }
        String inventoryCargoIds=inventory.getAdjustmentCargoId();

        ActionResult actionResult;
        if(inventoryService.saveNewInventory(inventory,inventoryCargoIds)){
            actionResult=new ActionResult();
        }else{
            actionResult=new ErrorResult();
        }
        
        List<InventoryShow> inventoryShows=new ArrayList<InventoryShow>();
        InventoryShowSearch inventoryShowSearch=new InventoryShowSearch();
        inventoryShowSearch.setInventoryId(inventory.getInventoryId());
        inventoryShows=inventoryShowService.queryListMP(inventoryShowSearch,null);
		
		model.addAttribute("inventoryShows", inventoryShows);
        model.addAttribute("inventory", inventory);
        model.addAttribute(ManageContainer.RESULTKEY, actionResult);

        return view(selDetailed);
    }

    @RequestMapping(value =deleteViewName, method = { RequestMethod.POST },produces="text/plain;charset=utf-8")
    public @ResponseBody String delete(String key){
        if(inventoryService.deleteFakeByKey(key)){
            return new JsonActionResult(ManageContainer.SUCCESS).toJson();
        }
        return new JsonActionResult(ManageContainer.ERROR).toJson();
    }
    
	@RequestMapping(value = queryCargosViewName, method = { RequestMethod.GET }, produces = "text/html;charset=UTF-8")
	public @ResponseBody String queryCargos(Model model,StockSearch search) {
		List<Stock> stocks= stockService.queryListMP(search,null);

		if (stocks.size()==0) {return null;}
		
		return "{\"data\":" + JsonUtils.writeValueAsString(stocks) + "}";
	}
	
    @RequestMapping(value = editDetailed, method = { RequestMethod.GET})
    public String editDetailed(Model model,String key){
        Inventory inventory=new Inventory();
		if (!StringUtils.isEmpty(key)) {
			inventory = inventoryService.queryModel(key);
			//暂时
			List<InventoryShow> inventoryShows=new ArrayList<InventoryShow>();
	        InventoryShowSearch inventoryShowSearch=new InventoryShowSearch();
	        inventoryShowSearch.setInventoryId(key);
	        inventoryShows=inventoryShowService.queryListMP(inventoryShowSearch,null);
			model.addAttribute("inventoryShows", inventoryShows);
		}
		model.addAttribute("inventory", inventory);
		return view(editDetailed);
    }
	
    @RequestMapping(value = selDetailed, method = { RequestMethod.GET})
    public String selDetailed(Model model,String key){
        Inventory inventory=new Inventory();
		if (!StringUtils.isEmpty(key)) {
			
			inventory = inventoryService.queryModel(key);
			//暂时
			List<InventoryShow> inventoryShows=new ArrayList<InventoryShow>();
	        InventoryShowSearch inventoryShowSearch=new InventoryShowSearch();
	        inventoryShowSearch.setInventoryId(key);
	        inventoryShows=inventoryShowService.queryListMP(inventoryShowSearch,null);
			model.addAttribute("inventoryShows", inventoryShows);
		
		}
		model.addAttribute("inventory", inventory);

		return view(selDetailed);
    }
    
	//保存草稿或最终的盘点单信息
	@RequestMapping(value = saveInventoryShow, method = { RequestMethod.POST }, produces = "text/html;charset=UTF-8")
	public String saveInventoryShow(Model model, Inventory inventory,InventoryCollocationInfo inventoryCollocationInfo) {
		inventory.setInventoryType(InventoryType.adjustment);
		if(!StringUtils.isEmpty(inventory.getInventoryId())){
			inventory.setModelStatus(ModelStatus.update);
		}
		ActionResult actionResult;
		//保存草稿或最终信息
		if (inventoryService.saveDraftInventoryInfo(inventory,inventoryCollocationInfo)) {
			actionResult = new ActionResult();
		} else {
			actionResult = new ErrorResult();
		}
		List<InventoryShow> inventoryShows=new ArrayList<InventoryShow>();
        InventoryShowSearch inventoryShowSearch=new InventoryShowSearch();
        inventoryShowSearch.setInventoryId(inventory.getInventoryId());
        inventoryShows=inventoryShowService.queryListMP(inventoryShowSearch,null);
		
		model.addAttribute("inventoryShows", inventoryShows);
		model.addAttribute("inventory", inventory);
		model.addAttribute(ManageContainer.RESULTKEY, actionResult);
		return view(editDetailed);
	}
}
